# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@file: routes_task.py
@time: 2024/11/5 20:18 
@desc: 

"""
import traceback
from flask import Blueprint, request, send_file, jsonify, redirect
from datetime import datetime
from tasks import choose_function
from db.model import TaskInfo, STATUS_TASK_DISCARD, STATUS_TASK_FAILED, STATUS_TASK_RUNNING, STATUS_TASK_INIT, \
    STATUS_TASK_SUCCESS
from .base_blue import get_result_tmp, sdb, auth
from config import TASKS_TIMEOUT
from errors.msg import TASK,SQL

tasks_bp = Blueprint('tasks', __name__)


@tasks_bp.route('/add/<string:script_id>', methods=['POST'])
@auth
def add(script_id, *args, **kwargs):
    """

    :return:
    """
    results = get_result_tmp()
    func_json = request.json
    func_json["script_id"] = script_id
    r = choose_function.delay(func_json)
    task_id = r.id
    conditions = [
        {"task_id": task_id,
         "project_id": func_json.get("script_id"),
         "extra": func_json,
         "user_id": kwargs["user_info"].id
         }
    ]
    res_db = sdb.insert(TaskInfo, conditions)
    if res_db is None:
        results["msg"] = SQL["1"].format(conditions)
        return jsonify(results)

    results["status"] = 0
    results["code"] = "SUCCESS"
    results["results"] = {"task_id": task_id}
    return jsonify(results)


@tasks_bp.route('/result', methods=['POST'])
@auth
def get_result(*args, **kwargs):
    """

    :return:
    """
    results = get_result_tmp()
    task_id = request.json.get("task_id")
    try:
        select_results = sdb.select(TaskInfo, conditions={"task_id": task_id})
        if select_results:
            for select_result in select_results:
                if (datetime.now() - select_result.create_time).seconds >= TASKS_TIMEOUT:
                    update_conditions = [{
                        "id": select_result.id,
                        "status": STATUS_TASK_DISCARD
                    }]
                    sdb.update(TaskInfo, update_conditions)
                    results["msg"] = TASK[STATUS_TASK_DISCARD].format(task_id)
                    return jsonify(results)
                status = select_result.status
                celery_result = select_result.result
                if status == STATUS_TASK_SUCCESS:
                    return f"static/download/{celery_result}"
                    # return send_file(f"static/download/{celery_result}", as_attachment=True)
                elif status == STATUS_TASK_RUNNING:
                    results["msg"] = TASK[status].format(task_id)
                elif status == STATUS_TASK_FAILED:
                    results["msg"] = TASK[status].format(task_id)
                elif status == STATUS_TASK_DISCARD:
                    results["msg"] = TASK[status].format(task_id)
                elif status == STATUS_TASK_INIT:
                    results["msg"] = TASK[status].format(task_id)
                else:
                    pass
                return jsonify(results)

        else:
            raise KeyError(f"task_id :{task_id} is not exists in mysql")
    except:
        results["msg"] = str(traceback.format_exc())
    return jsonify(results)
